// 该文件用于创建vuex中最核心的store
import Vue from 'vue'
// 引入VUEX
import Vuex from 'vuex'
// import user from './user'
import Cookie from 'js-cookie'
import { set } from 'cookie_js'
// import router from '../router'

Vue.use(Vuex)
// 用于响应组件中的动作
const actions = {
}
// 用于操作数据（state）
const mutations = {
    collapseMenu(state) {
        state.isCollapse = !state.isCollapse
    },
    textManage(state) {
        state.text = !state.text
    },
    selectMenu(state,val){
        if(val.name !== 'home'){
            state.currentMenu = val
            const result= state.tableList.findIndex(item => item.name === val.name)
            // console.log(result);
            if(result ===-1){
                state.tableList.push(val)
            }else{
                state.collapseMenu = null
            }
        }
    },
    setToken(state,val){
        state.token = val   
        Cookie.set('token',val)
    },
    clearToken(state){
        state.token = '',
        Cookie.remove('token')
    },
    getToken(state){
        state.token = state.token || Cookie.get('token')
    },
    setMenu(state,val){
        state.menu = val,
        Cookie.set('menu',JSON.stringify(val)) 
    },
    clearMenu(state){
        state.menu = [],
        Cookie.remove('menu')
    },
    addMenu(state,router){
        if(!Cookie.get('menu')){
            return
        }
        const menu = JSON.parse(Cookie.get('menu'))
        state.menu = menu
        const menuArray = []
        menu.forEach(item => {
            if(item.children){
                item.children = item.children.map(item =>{
                    item.componet = () => import(`../views/${item.url}`)
                    return item
                })
                menuArray.push(...item.children)
            }else{
                item.component = () => import(`../views/${item.url}`)
                menuArray.push(item)
            }
        });
        // 路由的动态添加
        menuArray.forEach(item=> {
        // console.log(menuArray);
            router.addRoute('layout',item)
        })
    }
    

    
}
// 用于存储数据
const state = {
    isCollapse: false,
    text: true,
    tableList: [
        {
            path: '/',
            name: 'home',
            label: '首页',
            icon: 'home'
        }
    ],
    currentMenu: null,
    token:'',
    menu:[],

}

export default new Vuex.Store({
    actions,
    mutations,
    state,
    // modules:{
    //     user
    // }
})

